package com.xjz.job.cycle;

import cn.hutool.core.collection.CollUtil;
import com.xjz.esdao.PostEsDao;
import com.xjz.mapper.PostMapper;
import com.xjz.model.dto.post.PostEsDTO;
import com.xjz.model.entity.Post;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: IncSyncPostToEs
 * Package: com.xjz.job
 * Description:
 *  增量同步到es
 * @Author 许小健
 * @Create 2025/8/15 11:54
 * @Version 1.0
 */
@Component
@Slf4j
public class IncSyncPostToEs {
    @Resource
    private PostMapper postMapper;

    @Resource
    private PostEsDao postEsDao;

    @Scheduled(fixedRate = 60 * 1000)
    public void run() {
        //查询近五分钟的数据
        Date fiveMinuteAgoDate = new Date(new Date().getTime() - 5 * 60 * 1000L);
        List<Post> postList = postMapper.listPostWithDelete(fiveMinuteAgoDate);
        if (CollUtil.isEmpty(postList)) {
            log.info("no inc post");
            return;
        }

        List<PostEsDTO> postEsDTOList = postList.stream().map(PostEsDTO::objToDto).collect(Collectors.toList());
        final int pageSize = 500;
        int total = postEsDTOList.size();
        log.info("IncSyncPostToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize,total);
            log.info("sync from {} to {}", i, end);
            postEsDao.saveAll(postEsDTOList.subList(i,end));
        }
        log.info("IncSyncPostToEs end, total {}", total);
    }
}
